using GEM.Application.Contracts;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using GEM.Application.Contracts.Jwt;

namespace GEM.Infrastructure.Jwt;

public class JwtTokenService : IJwtTokenService
{
    public readonly JwtSettings _Settings;
    public JwtTokenService(IOptions<JwtSettings> options)
    {
        _Settings = options.Value;
    }

    public string GenerateToken(Guid userId, string username, IEnumerable<string> roles)
    {
        var claims = new List<Claim>
        {
            new Claim("userId",userId.ToString()),
            new Claim(ClaimTypes.Name,username)
            // 可扩展角色等
        };

        // 添加角色到声明中
        foreach (var role in roles)
        {
            claims.Add(new Claim(ClaimTypes.Role, role));
        }

        // 生成安全密钥
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_Settings.Key));
        // 创建签名凭证  (SecurityAlgorithms.HmacSha256：使用 HMAC-SHA256 算法签名)
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        // 构建 JWT
        var token = new JwtSecurityToken(
            _Settings.Issuer,
            _Settings.Audience,
            claims,
            expires: DateTime.UtcNow.AddMinutes(_Settings.ExpireMinutes),
            signingCredentials: creds);

        // 生成令牌字符串并返回
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}